import axios from 'axios'
import { Toast } from 'vant'
import store from '@/store/index.js'
import router from '@/router/index.js'
import { authorizationsPut } from '@/api/user.js'

const _axios = axios.create({
  baseURL: process.env.VUE_APP_URL
})

_axios.interceptors.request.use(
  config => {
    if (!config.noToken) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  error => Promise.reject(error)
)

_axios.interceptors.response.use(
  res => res.data,
  async error => {
    // 统一解决 401（token失效）问题
    if (error.response.status === 401) {
      try {
        // token 失效，通过 refresh_token 刷新 token
        const resToken = await authorizationsPut()
        // 保存新 token
        store.commit('user/setToken', resToken.data.token)
        // 让之前的请求正常进行
        return _axios(error.config)
      } catch {
        // refresh_token 也失效，提示并跳转到登录页
        if (error.response.data && error.response.data.message) {
          Toast.fail(error.response.data.message)
        }
        store.commit('user/setToken', '')
        router.push('/login?redirect=' + router.currentRoute.fullPath)
        // router.push('/login?redirect=' + location.href.split('#')[1])
      }
    } else {
      // 除 401 之外的错误正常提示
      if (error.response.data && error.response.data.message) {
        Toast.fail(error.response.data.message)
      }
    }
    return Promise.reject(error)
  }
)

export default _axios
